package com.base.maintain;

import java.io.File;
import java.io.FileFilter;
import java.text.ParseException;
import java.util.Date;

import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author yanjiaqiang
 * @date 2010-12-31
 * @version $Id: FileRemoveTask.java 7 2011-07-15 04:24:04Z JiaqiangYan@gmail.com $
 */
public class FileRemoveTask implements Runnable {

	private static Logger logger = LoggerFactory.getLogger(FileRemoveTask.class);

	private File rootDir;
	private FileFilter filter;
	private long oldTimemills;

	private long delSize;
	private long delNum;
	private long deltime;

	public FileRemoveTask(String dirPath, String timeStr) {
		this(new File(dirPath), timeStr);
	}

	public FileRemoveTask(File dir, String timeStr) {
		this(dir, timeStr, null);
	}

	public FileRemoveTask(File dir, String timeStr, FileFilter filter) {
		super();
		this.rootDir = dir;
		this.filter = filter;

		try {
			oldTimemills = DateUtils.parseDate(timeStr, new String[] { "yyyy-MM-dd" }).getTime();
		} catch (ParseException e) {
			logger.error(timeStr + "时间不对", e);
			throw new RuntimeException(e);
		}
	}

	private boolean remove(File file, long beforeTimeMills) {

		if (isOldFile(file, beforeTimeMills)) {
			return file.delete();
		}
		return false;
	}

	private boolean isOldFile(File file, long oldTime) {
		return file.lastModified() < oldTime;
	}

	@Override
	public void run() {
		long start = System.currentTimeMillis();
		recursiveDelete(rootDir);
		deltime = (System.currentTimeMillis() - start);

		Date d = new Date(oldTimemills);
		long size = delSize / (1024 * 1024);

		logger.info("删除" + rootDir.getAbsolutePath() + "时间早于" + d.toLocaleString() + " 删除文件数:" + delNum + " 删除文件大小："
				+ size + "M 耗费时间:" + deltime);
	}

	private void recursiveDelete(File file) {

		if (file.isFile()) {
			long size = file.length();
			long lastmodified = file.lastModified();
			boolean hasDel = remove(file, oldTimemills);

			if (hasDel) {
				delSize += size;
				delNum++;
				logger.info("delete file " + file.getAbsolutePath() + " lastmodified:" + lastmodified);
			}
			return;
		}

		File[] subFiles = null;
		if (filter != null) {
			subFiles = file.listFiles(filter);
		} else {
			subFiles = file.listFiles();
		}

		if (subFiles != null) {
			for (File subfile : subFiles) {
				recursiveDelete(subfile);
			}
		}

	}
}
